package com.industrial.premu.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.util.StringUtils;
import com.industrial.common.core.utils.bean.BeanUtils;
import com.industrial.common.core.utils.uuid.IdUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportCustomIndexLj;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.dto.PreMuCustomIndicatorDto;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportCustomIndexLjMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.service.IPreMuImportCustomIndexLjService;
import com.industrial.premu.service.IPreMuImportLogService;
import com.industrial.premu.vo.PreMuImportCustomIndexLjVo;
import com.industrial.system.api.domain.SysUser;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.industrial.premu.mapper.PreMuCustomIndicatorMapper;
import com.industrial.premu.domain.PreMuCustomIndicator;
import com.industrial.premu.service.IPreMuCustomIndicatorService;
import org.springframework.transaction.annotation.Transactional;

import static com.industrial.common.core.utils.PageUtils.startPage;

/**
 * 亩产自定义指标Service业务层处理
 * 
 * @author ZhouS
 * @date 2024-01-23
 */
@Service
public class PreMuCustomIndicatorServiceImpl implements IPreMuCustomIndicatorService 
{
    @Autowired
    private PreMuCustomIndicatorMapper preMuCustomIndicatorMapper;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    @Autowired
    private IPreMuImportCustomIndexLjService preMuImportCustomIndexLjService;

    @Autowired
    private PreMuImportCustomIndexLjMapper preMuImportCustomIndexLjMapper;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;



    /**
     * 查询亩产自定义指标
     * 
     * @param id 亩产自定义指标主键
     * @return 亩产自定义指标
     */
    @Override
    public PreMuCustomIndicator selectPreMuCustomIndicatorById(String id)
    {
        return preMuCustomIndicatorMapper.selectPreMuCustomIndicatorById(id);
    }

    /**
     * 查询亩产自定义指标列表
     * 
     * @param preMuCustomIndicator 亩产自定义指标
     * @return 亩产自定义指标
     */
    @Override
    public List<PreMuCustomIndicator> selectPreMuCustomIndicatorList(PreMuCustomIndicator preMuCustomIndicator)
    {
        return preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(preMuCustomIndicator);
    }

    /**
     * 新增亩产自定义指标
     * 
     * @param preMuCustomIndicator 亩产自定义指标
     * @return 结果
     */
    @Override
    public int insertPreMuCustomIndicator(PreMuCustomIndicator preMuCustomIndicator)
    {
        String district= SecurityUtils.getLoginUser().getSysUser().getDistrict();

        preMuCustomIndicator.setCounty(district);
        preMuCustomIndicator.setId(IdUtils.simpleUUID());
        preMuCustomIndicator.setCreateDate(new Date());

        return preMuCustomIndicatorMapper.insertPreMuCustomIndicator(preMuCustomIndicator);
    }

    /**
     * 修改亩产自定义指标
     * 
     * @param preMuCustomIndicator 亩产自定义指标
     * @return 结果
     */
    @Override
    public int updatePreMuCustomIndicator(PreMuCustomIndicator preMuCustomIndicator)
    {
        return preMuCustomIndicatorMapper.updatePreMuCustomIndicator(preMuCustomIndicator);
    }

    /**
     * 批量删除亩产自定义指标
     * 
     * @param ids 需要删除的亩产自定义指标主键
     * @return 结果
     */
    @Override
    public int deletePreMuCustomIndicatorByIds(String[] ids)
    {
        return preMuCustomIndicatorMapper.deletePreMuCustomIndicatorByIds(ids);
    }

    /**
     * 删除亩产自定义指标信息
     * 
     * @param id 亩产自定义指标主键
     * @return 结果
     */
    @Override
    public int deletePreMuCustomIndicatorById(String id)
    {
        return preMuCustomIndicatorMapper.deletePreMuCustomIndicatorById(id);
    }

    @Override
    public BigDecimal getSumScoreByCountyAndCompanyType(PreMuCustomIndicator paramMap) {
        return preMuCustomIndicatorMapper.getSumScoreByCountyAndCompanyType(paramMap);
    }

    @Override
    public List<PreMuImportCustomIndexLj> selectImportList(PreMuCustomIndicatorDto queryParams) {
        PreMuCustomIndicator param = new PreMuCustomIndicator();
        BeanUtils.copyProperties(queryParams, param);
        List<PreMuCustomIndicator> preMuCustomIndicators = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(param);
        if(preMuCustomIndicators == null || preMuCustomIndicators.isEmpty()){
            return new ArrayList<PreMuImportCustomIndexLj>();
        }
        List<String> customIds = preMuCustomIndicators.stream().map(PreMuCustomIndicator::getId).distinct().collect(Collectors.toList());
        startPage();
        List<PreMuImportCustomIndexLj> res = preMuImportCustomIndexLjMapper.selectPreMuImportCustomIndexLjByPkIdAndCompanyName(customIds, queryParams.getCompanyName());
        return res;
    }
    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;
    /**
     * 删除规上自定义指标
     * @param queryParams
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult removeData(PreMuCustomIndicator queryParams,String deptCode) {
        List<PreMuCustomIndicator> preMuCustomIndicators = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(queryParams);
        if(preMuCustomIndicators == null || preMuCustomIndicators.isEmpty()){
            return AjaxResult.warn("没有找到数据");
        }
        List<String> collect = preMuCustomIndicators.stream().map(PreMuCustomIndicator::getId).distinct().collect(Collectors.toList());
        preMuImportCustomIndexLjMapper.deletePReMUImportCustomIndexLjByPkIds(collect);

        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(queryParams.getYear());
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
        return AjaxResult.success();
    }




    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importData(String year, String companyType, InputStream is) {

        int successNum = 0;
        int updateNum = 0;
        try{
            Workbook wb = WorkbookFactory.create(is);

            //加载所有的指标
            PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
            queryParams.setYear(year);
            queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
            queryParams.setCompanyType(companyType);
            List<PreMuCustomIndicator> indicatorDOList = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorAndUnitList(queryParams);
            if(indicatorDOList == null || indicatorDOList.isEmpty()){
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("allMsg","没有找到该区县所设置的自定义指标");
                return AjaxResult.success(resultMap);
            }
            Map<String, String> indexNameToIdMapping = indicatorDOList.stream().collect(Collectors.toMap(k -> k.getName(), v -> v.getId()));
            //指标名称和列对应关系
            Map<Integer,String> indexNameToCol = new HashMap<>();
            if(wb!= null){
                Sheet sheet = wb.getSheetAt(0);
                if(sheet != null){
                    Row headerRow = sheet.getRow(0);
                    if(headerRow != null){
                        int idx = 0;
                        boolean shuiwufalg = false;
                        for(idx=0;idx<headerRow.getLastCellNum();idx++){
                            Cell indicatorTabCell = headerRow.getCell(2+idx);
                            if(indicatorTabCell != null){
                                if(indicatorTabCell.getCellTypeEnum().equals(CellType.STRING)){
                                    String indicatorTabValue = indicatorTabCell.getStringCellValue();

                                    if(indicatorTabValue.contains("(")){
                                        indicatorTabValue = indicatorTabValue.split("\\(")[0];
                                    }
                                    indexNameToCol.put(2+idx,indicatorTabValue);
                                    if ("用水量".equals(indicatorDOList.get(idx).getName())){
                                        shuiwufalg = true;
                                    }
                                    if(indicatorTabValue == null || "".equals(indicatorTabValue)){
                                        break;
                                    }else{
                                        if(!indicatorDOList.get(idx).getName().equals(indicatorTabValue.trim())){
                                            Map<String,String> resultMap = new HashMap<>();
                                            resultMap.put("allMsg","模板过期，请重新下载数据模板！");
                                            return AjaxResult.success(resultMap);
                                        }
                                    }
                                }
                            }else{
                                break;
                            }
                        }
                        if(!shuiwufalg && idx != indicatorDOList.size()){
                            Map<String,String> resultMap = new HashMap<>();
                            resultMap.put("allMsg","模板过期，请重新下载数据模板！");
                            return AjaxResult.success(resultMap);
                        }else if(shuiwufalg && idx != (indicatorDOList.size())){
                            Map<String,String> resultMap = new HashMap<>();
                            resultMap.put("allMsg","模板过期，请重新下载数据模板！");
                            return AjaxResult.success(resultMap);
                        }

                        Map<String, String> comMap = new HashMap<String, String>();
                        List<PreMuImportCustomIndexLj> existList = new ArrayList<PreMuImportCustomIndexLj>();
                        List<String> comIdList = new ArrayList<String>();

                        PreMuCompanyInfo queryCompanyInfoParams = new PreMuCompanyInfo();
                        queryCompanyInfoParams.setYear(year);
                        queryCompanyInfoParams.setCompanyType(companyType);
                        queryCompanyInfoParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                        List<PreMuCompanyInfo> comList = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(queryCompanyInfoParams);
                        if(comList != null && !comList.isEmpty()){
                            comList.forEach(com ->{
                                if(com.getUscc() != null && !"".equals(com.getUscc())) {
                                    comMap.put(com.getUscc().trim(), com.getId());
                                    comIdList.add(com.getId());
                                }
                            });
                        }
                        //这个里面保存的是企业Id和baseId
                        existList = preMuImportCustomIndexLjService.getImportValueExistList(year, companyType,SecurityUtils.getLoginUser().getSysUser().getDistrict(),comIdList);
                        Map<String, String> enterIdToBaseIdLjMap = new HashMap<>();
                        if(existList != null && !existList.isEmpty()){
                            enterIdToBaseIdLjMap = existList.stream().collect(Collectors.toMap(k -> {
                                String enterId = k.getEnterId();
                                String indexId = k.getIndexId();
                                return enterId + "@" + indexId;
                            }, v -> v.getBaseId()));
                        }

                        List<PreMuImportCustomIndexLj> updateList = new ArrayList<>();
                        List<PreMuImportCustomIndexLj> inserList = new ArrayList<>();

                        for(int i=0;i<sheet.getLastRowNum();i++) {
                            Row valueRow = sheet.getRow(i + 1);
                            if(valueRow != null){
                                Cell usccCell = valueRow.getCell(0);
                                if(usccCell !=null) {
                                    if (usccCell.getCellTypeEnum().equals(CellType.STRING)) {
                                        String uscc = usccCell.getStringCellValue();
                                        if(uscc == null || "".equals(uscc)){
                                            Map<String,String> resultMap = new HashMap<>();
                                            resultMap.put("allMsg","统一社会信用代码有错误，请检查数据!");
                                            return AjaxResult.success(resultMap);
                                        }else{
                                            uscc = uscc.trim();
                                        }
                                        if(!comMap.containsKey(uscc)){
                                            Map<String,String> resultMap = new HashMap<>();
                                            resultMap.put("allMsg","统一社会信用代码与企业名单不符，请检查数据!");
                                            return AjaxResult.success(resultMap);
                                        }

                                        for(int currentCol = 2; currentCol < valueRow.getLastCellNum(); currentCol ++){

                                            PreMuImportCustomIndexLj temp = new PreMuImportCustomIndexLj();
                                            String indexName = indexNameToCol.get(currentCol);
                                            String indexId = indexNameToIdMapping.get(indexName);
                                            String enterId = comMap.get(uscc);

                                            //如果为真，说明表中有这个企业对应的指标信息
                                            if(enterIdToBaseIdLjMap.containsKey(enterId + "@" + indexId)){
                                                temp.setBaseId(enterIdToBaseIdLjMap.get(enterId + "@" + indexId));
                                                Cell currentCell = valueRow.getCell(currentCol);
                                                if(currentCell.getCellTypeEnum() == CellType.STRING){
                                                    String stringCellValue = currentCell.getStringCellValue();
                                                    if(StringUtils.isNotBlank(stringCellValue)){
                                                        BigDecimal bigDecimal = new BigDecimal(stringCellValue);
                                                        BigDecimal bigDecimal1 = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                        temp.setIndexValue(bigDecimal1.toString());
                                                    }else{
                                                        temp.setIndexValue("");
                                                    }

                                                }else if(currentCell.getCellTypeEnum() == CellType.FORMULA){
                                                    FormulaEvaluator evaluator = currentCell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
                                                    evaluator.evaluateFormulaCellEnum(currentCell);
                                                    CellValue cellValue = evaluator.evaluate(currentCell);
                                                    Double celldata = cellValue.getNumberValue();
                                                    BigDecimal bg = new BigDecimal(celldata).setScale(2, BigDecimal.ROUND_HALF_UP);
                                                    temp.setIndexValue(bg.toString());
                                                } else{
                                                    String numericCellValueStr = String.valueOf(currentCell.getNumericCellValue());
                                                    if(StringUtils.isNotBlank(numericCellValueStr)){
                                                        BigDecimal tempBig = new BigDecimal(numericCellValueStr);
                                                        BigDecimal scaleBig = tempBig.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                        temp.setIndexValue(scaleBig.toString());
                                                    }else{
                                                        temp.setIndexValue("");
                                                    }
                                                }
                                                temp.setDelFlag("0");
                                                updateList.add(temp);
                                            }else{
                                                temp.setBaseId(IdUtils.simpleUUID());
                                                temp.setIndexId(indexId);
                                                temp.setIndexName(indexName);
                                                temp.setEnterId(enterId);
                                                temp.setYear(year);

                                                Cell currentCell = valueRow.getCell(currentCol);
                                                if(currentCell.getCellTypeEnum() == CellType.STRING){
                                                    String stringCellValue = currentCell.getStringCellValue();
                                                    if(StringUtils.isNotBlank(stringCellValue)){
                                                        BigDecimal tempBig = new BigDecimal(stringCellValue);
                                                        BigDecimal scaleBig = tempBig.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                        temp.setIndexValue(scaleBig.toString());
                                                    }else{
                                                        temp.setIndexValue("");
                                                    }

                                                }else if(currentCell.getCellTypeEnum() == CellType.FORMULA){
                                                    FormulaEvaluator evaluator = currentCell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
                                                    evaluator.evaluateFormulaCellEnum(currentCell);
                                                    CellValue cellValue = evaluator.evaluate(currentCell);
                                                    Double celldata = cellValue.getNumberValue();
                                                    BigDecimal bg = new BigDecimal(celldata).setScale(2, BigDecimal.ROUND_HALF_UP);
                                                    temp.setIndexValue(bg.toString());
                                                } else{
                                                    String numericCellValueStr = String.valueOf(currentCell.getNumericCellValue());
                                                    if(StringUtils.isNotBlank(numericCellValueStr)){
                                                        BigDecimal tempBig = new BigDecimal(numericCellValueStr);
                                                        BigDecimal scaleBig = tempBig.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                        temp.setIndexValue(scaleBig.toString());
                                                    }else{
                                                        temp.setIndexValue("");
                                                    }
                                                }
                                                inserList.add(temp);
                                            }
                                        }

                                    }
                                }else{
                                    throw new RuntimeException("检查到当前表中有企业的社会信用代码不存在,停止导入");
                                }
                            }
                            if(inserList.size() >= 300){
                                int importRowCount = preMuImportCustomIndexLjService.batchInsert(inserList);
                                successNum += inserList.size();
                                inserList.clear();
                            }
                            if(updateList.size() >= 300){
                                int updateRowCount = preMuImportCustomIndexLjService.batchUpdate(updateList);
                                successNum += updateList.size();
                                updateNum += updateList.size();
                                updateList.clear();
                            }
                        }

                        if(!inserList.isEmpty()){
                            int importRowCount = preMuImportCustomIndexLjService.batchInsert(inserList);
                            successNum += inserList.size();
                            inserList.clear();
                        }
                        if(!updateList.isEmpty()){
                            int updateRowCount = preMuImportCustomIndexLjService.batchUpdate(updateList);
                            successNum += updateList.size();
                            updateNum += updateList.size();
                            updateList.clear();
                        }
                    }
                }
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("msg","恭喜您，共"+successNum+"条数据导入成功！");
                resultMap.put("allMsg","恭喜您，共"+successNum+"条数据导入成功！");
                resultMap.put("sum",String.valueOf(successNum));
                resultMap.put("updateNum",String.valueOf(updateNum));
                return AjaxResult.success(resultMap);
            }else{
                return AjaxResult.warn("Excel未加载成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("导入失败");
        }
    }

    @Override
    public Workbook createTemplateWb(PreMuCustomIndicator paramMap) {
        LocalDate localDate = LocalDate.now();
        paramMap.setYear(String.valueOf(localDate.getYear()-1));
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();

        List<PreMuCustomIndicator> colList = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(paramMap);

        Workbook wb = new SXSSFWorkbook(500);
        XSSFCellStyle headerStyle = (XSSFCellStyle) wb.createCellStyle();
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);    //设置填充方案
        headerStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(180,198,231)));  //设置填充颜色
        SXSSFSheet sheet = ((SXSSFWorkbook) wb).createSheet("自定义指标");
        sheet.createFreezePane( 0, 1, 0, 1 );
        SXSSFRow row = sheet.createRow(0);
        SXSSFCell usccNameCell = row.createCell(0, CellType.STRING);
        usccNameCell.setCellStyle(headerStyle);
        usccNameCell.setCellValue("统一社会信用代码");
        SXSSFCell companyNameCell = row.createCell(1, CellType.STRING);
        companyNameCell.setCellStyle(headerStyle);
        companyNameCell.setCellValue("企业全称");

        for(int i=0;i<colList.size();i++){
            PreMuCustomIndicator mcCustomIndicatorDO = colList.get(i);
            SXSSFCell indicatorNameCell = row.createCell(2+i, CellType.STRING);
            //生成模板时，在自定义指标列表里剔除单位水耗销售收入指标（该指标不在此处导入）
            if (!mcCustomIndicatorDO.getName().equals("单位水耗销售收入")){
                if(mcCustomIndicatorDO.getUnit() != null && !"".equals(mcCustomIndicatorDO.getUnit())){
                    indicatorNameCell.setCellValue(mcCustomIndicatorDO.getName()+"("+mcCustomIndicatorDO.getUnit()+")");
                }else{
                    indicatorNameCell.setCellValue(mcCustomIndicatorDO.getName());
                }

                indicatorNameCell.setCellStyle(headerStyle);
            }
        }

        PreMuCompanyInfo queryParams = new PreMuCompanyInfo();
        queryParams.setCounty(paramMap.getCounty());
        queryParams.setYear(paramMap.getYear());
        queryParams.setCompanyType(paramMap.getCompanyType());
        List<PreMuCompanyInfo> comList = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(queryParams);
        for(int i=0;i<comList.size();i++) {
            PreMuCompanyInfo companyInfoDO = comList.get(i);
            SXSSFRow comRow = sheet.createRow(i + 1);
            SXSSFCell usccCell = comRow.createCell(0, CellType.STRING);
            SXSSFCell comNameCell = comRow.createCell(1, CellType.STRING);
            usccCell.setCellValue(companyInfoDO.getUscc());
            comNameCell.setCellValue(companyInfoDO.getCompanyName());
        }
        return wb;
    }

    @Override
    public List<PreMuImportCustomIndexLjVo> getIndexLjVoList(PreMuImportCustomIndexLj indexLj) {


        return preMuCustomIndicatorMapper.getIndexLjVoList(indexLj);
    }
}
